Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

135
Visualizações
API issue | URL with parameter

I have an issue with my Delete function, it is deleting always the last data and not the desired data.

Here's my API - DELETE function:

Function to delete the data

app.delete("/api/theTasks/:id", (req, res) => {
    let taskToRemove = Items.find(p => p.id == parseInt(req.params.id));
    let index = Items.indexOf(taskToRemove);
    Items.splice(index, 1);
    res.json(taskToRemove);
});
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

Problem:

  1. find also return undefined If it does not find the item.
  2. when you search for the undefined index it'll return -1
  3. if you pass -1 to splice It'll always remove the last element.

Use array filter,

app.delete("/api/theTasks/:id", (req, res) => {
  const result = Items.filter((p) => p.id === parseInt(req.params.id));

  if (result.length === 0) res.status(404).json({ error: "Item not found" });
  res.json(result);
});
about 4 years ago · Juan Pablo Isaza Relatório

0

My guess is that the task is not found and index ends up being -1, so you end up calling:

Items.splice(-1, 1);

which removes the last element of Items.

You can fix the issue by checking if the item was found and only deleting it if that is true.

app.delete("/api/theTasks/:id", (req, res) => {
    let taskToRemove = Items.find(p => p.id == parseInt(req.params.id));
    if (taskToRemove) {
        let index = Items.indexOf(taskToRemove);
        Items.splice(index, 1);
        res.json(taskToRemove);
    } else {
        res.status(404).json({ error: 'Item not found' });
    }

});
about 4 years ago · Juan Pablo Isaza Relatório

0

get index is -1; you should check it before splice; or use filter

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda